<?php
class CARXCMSPlugMyAdmin  extends CmsPlugin2
{
	var $table;
	var $t;
	var $decode;
	var $perPage = 10;
	var $err = array(
	'1' => 'err|Неверный формат Алиаса таблицы',
	'2' => 'err|Имя таблицы может состоять только из латинских букв. Минимальная длинна имени 3 символа',
	'3' => 'err|Поле Алиас Таблицы являеться обязательным и не может быть пустым!',
	'4' => 'err|Поле Имя таблицы являеться обязательным и не может быть пустым!',
	'5' => 'err|Ошибка создания таблицы!',
	'6' => 'Таблица создана. Обновите страницу',
	'7' => 'err|У таблицы контента должно быть хоть одно поле краткого описания',
	'9' => 'err|Имя плагина должно состоять ТОЛЬКО из англ букв. Длинна не менее 3 символов',
	'10' => 'err|Описание плагина может состоять только из англ и русс букв',
	);
	//и суслику ясна что имя таблицы и асоц.масив полей.
	function insert_($table_name,$fields)
	{
		$this->table->Close();
		$this->table->m_tables = ARX_DB_TABLE_PREFIX.$table_name;
		foreach ($fields as $key=>$val)
		{
			if (! get_magic_quotes_gpc ())
			{
				$this->table->SetField($key,$this->utf8_urldecode($val, ENT_COMPAT, "UTF-8"));
			}
			else
			{
				$this->table->SetField($key,$this->utf8_urldecode($val, ENT_COMPAT, "UTF-8"));
			}
		}

		$this->table->Insert();
	}

	function utf8_urldecode($str,$quotes,$charset){
		$str =  preg_replace_callback('/%u([0-9a-f]{4})/i',create_function('$arr','return "&#".hexdec($arr[1]).";";'),$str);
		return html_entity_decode($str,$quotes,$charset);
	}

	//читай выше
	function update_($table_name,$fields,$condition)
	{
		$this->table->Close();
		//            $this->table->m_tables = ARX_DB_TABLE_PREFIX.$table_name;
		$this->table->m_tables = ARX_DB_TABLE_PREFIX.$table_name;
		$this->table->m_filter = $condition;
		foreach ($fields as $key=>$val)
		{
			if (! get_magic_quotes_gpc ())
			{
				$this->table->SetField($key,$this->utf8_urldecode($val, ENT_COMPAT, "UTF-8"));
			}
			else
			{
				//                    $this->table->SetField($key,urldecode($this->decode->_ucs2EntitiesDecode($val)));
				$this->table->SetField($key,$this->utf8_urldecode($val, ENT_COMPAT, "UTF-8"));
			}
		}

		$this->table->Update();
	}

	//всеплагиновый carxtable ПОЛНАЯ ХУЕТА
	//0 - fetchrows
	//1 - fetchrow
	//2 - значение поля $field
	//3 - нихуя не возвращаем
	function sql($q,$mode = 0,$field = "")
	{
		mysql_query("SET NAMES `".DATABASE_CHARSET."`");
		$this->table->Close();
		if ($this->table->m_lastError)
		{
			$this->table = new CARXTable();
		}
		$this->table->SetSql($q);
		$this->table->Open();
		if ($this->table->m_lastError != '') return 0;
		switch($mode)
		{
			case 0: return $this->table->FetchRows();
			case 1: return $this->table->FetchRow();
			case 2:
				{
					$tmp = $this->table->FetchRow();
					return $tmp[$field];
				}
			case 3: return 1;
		}
	}

	//по имени таблицы берем его алиас
	function getTableAlias($tb)
	{
		return $this->sql("select alias from ".ARX_DB_TABLE_PREFIX."admin_tableAlias where tabl = '$tb'",2,'alias');
	}

	function getTables($tableName)
	{
		//            return $this->sql("select * from ".ARX_DB_TABLE_PREFIX."admin_tableAlias where tabl <> '$tableName'" );
		return $this->sql("select * from ".ARX_DB_TABLE_PREFIX."admin_tableAlias" );
	}
	//списко всех таблиц текущей базы. с префиксом
	/*
	function getTableList($prefix = 'cnt')
	{
	$prefix = DB_DATABASE."__".$prefix;
	$db_list=mysql_list_dbs($this->table->m_hostID);
	while($r_db=mysql_fetch_object($db_list))
	{
	if ($r_db->Database == DB_DATABASE)
	{
	$t_list=mysql_list_tables($r_db->Database);
	for($i=0;$i<mysql_num_rows($t_list);$i++)
	{
	$tb = mysql_tablename($t_list,$i);
	if (strncmp($prefix,$tb, strlen($prefix)) == 0)
	$arr[$tb] = $this->getTableAlias($tb);
	}
	}
	}
	return $arr;
	}
	*/
	// function getTableList($prefix = 'cnt')
	//          {
	//            $prefix = ARX_DB_TABLE_PREFIX."".$prefix;
	//            $db_list=mysql_list_dbs($this->table->m_hostID);
	//            while($r_db=mysql_fetch_object($db_list))
	//              {
	//               if ($r_db->Database == DB_DATABASE)
	//                 {
	//                   $t_list=mysql_list_tables($r_db->Database);
	//                   for($i=0;$i<mysql_num_rows($t_list);$i++)
	//                     {
	//                       $tb = mysql_tablename($t_list,$i);
	//                       if (strncmp($prefix,$tb, strlen($prefix)) == 0)
	//                       $arr[$tb] = $this->getTableAlias($tb);
	//                     }
	//                 }
	//              }
	//
	//            return $arr;
	//          }

	function getTableList($parent_id=0,$module=false)
	{
		$tables=array();
		if ($module>0) $filtPart=" AND module=$module";
		//рекурсивно ищем таблицы и возвращаем их ввиде вложенного массива
		$res=mysql_query("SELECT * FROM ".ARX_DB_TABLE_PREFIX."admin_tableAlias WHERE parent_id=$parent_id $filtPart");
		while($row=mysql_fetch_assoc($res))
		{
			//ищем потомков
			$children=$this->getTableList($row['id']);
			if($children) $row['sub']=$children;
			$tables[]=$row;
		}
		return $tables;
	}

	function getTableListFetched($module)
	{
		global $smarty;
		$smarty->assign("tree",$this->getTableList(0,$module));
		return $smarty->fetch($_SERVER['DOCUMENT_ROOT'].'/control/myadmin/myAdmin/tableTree.sm');
	}

	function getValidationFunc()
	{
		$table = new CARXTable('cnt_validators');
		$data = $table->FetchRows();
		return $data;
	}

	function getFieldTypes()
	{
		return $this->sql("select * from ".ARX_DB_TABLE_PREFIX."admin_fieldTypes");
	}

	function getFields($tableName, $type=0)
	{
		$type_def=($type!=0)? "AND type='$type'" : '';
		$arr = ($this->sql("select * from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where tabl = '$tableName' $type_def order by ord"));
		foreach ($arr as $key=>$val)
		{
			if ($val['type'] == 6 || $val['type'] == '9' || $val['type'] == '11')
			{
				if ($val['comboField'] != 'id')
				{
					$arr[$key]['comboId'] = $this->sql("select id from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where tabl='$val[combo]' and field = '$val[comboField]'",2,'id');
				}
				else
				{
					$arr[$key]['comboId'] = $val['combo'];
				}
			}
		}
		return $arr;
	}
	//если выбрана таблица  - фукнция обработки этого
	function tableInfo()
	{
		$tableName = $this->t;
		$tableAlias = $this->sql("select alias from ".ARX_DB_TABLE_PREFIX."admin_tableAlias where tabl = '$tableName'",2,'alias');
		if (!$tableName) return "Таблицы несуществует";
		global $smarty;
		$smarty->assign("fields",$this->getFields($tableName));
		$smarty->assign("fieldTypes",$this->getFieldTypes());
		$smarty->assign("tableAlias",$tableAlias);
		$comboTables = $this->getTables($tableName);
		foreach ($comboTables as $key=>$val)
		{
			$comboTables[$key]['iitems'] = $this->sql("select id,alias,field from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where tabl='$val[tabl]'");
		}
		$smarty->assign('maxOrd',$this->sql("select max(ord) as maxx from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where tabl = '$tableName'",2,'maxx'));
		$smarty->assign('minOrd',$this->sql("select min(ord) as minn from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where tabl = '$tableName'",2,'minn'));
		$smarty->assign("comboTables",$comboTables);
		$smarty->assign('validFunc',$this->getValidationFunc());
		$smarty->assign("table_select", $this->table_select(0, '', $tableName));
		$smarty->assign("table_select_extra", $this->table_select());
		return $smarty->fetch("myAdmin/tableInfo.sm");
	}
	function errF($n)
	{
		if (!$n) return;
		echo $this->err[$n];
		exit;
	}
	//для создания новой таблицы
	function newTable()
	{
		global $smarty;

		$table_alias = r_p("table_alias");
		$table_name = r_p("table_name");
		$table_parent_id = r_p("table_parent_id");
		if (!$table_alias) return $this->errF(3);
		if (!$table_name) return $this->errF(4);
		if (!preg_match("/^(?:[a-zA-Z\s]+)|(?:[а-яА-Я\s])$/",trim($table_alias))) return $this->errF(1);
		if (!preg_match("/^[a-zA-Z]{3,}$/", trim($table_name))) return $this->errF(2);

		$table_name = ARX_DB_TABLE_PREFIX."cnt_".$table_name;
		if (!$this->sql("CREATE TABLE $table_name (`id` INT NOT NULL AUTO_INCREMENT ,`time` INT NOT NULL , `letime` INT NOT NULL, PRIMARY KEY ( `id` ))",3))
		$this->errF(5);
		$this->insert_("admin_tableAlias",array("tabl"=>$table_name,"alias"=>$table_alias, "parent_id"=>$table_parent_id));
		$this->errF(6);
	}

	//мля ну хуле - удаляем таблицу наверное
	function deleteTable()
	{
		$table = $this->t;
		//            $table = r_p("table");
		if (!$table) return;
		$parent=mysql_fetch_assoc(mysql_query("SELECT * FROM ".ARX_DB_TABLE_PREFIX."admin_tableAlias WHERE tabl='$table'"));
		$this->sql("UPDATE ".ARX_DB_TABLE_PREFIX."admin_tableAlias SET parent_id=$parent[parent_id] WHERE parent_id=$parent[id]");
		$this->sql("DROP TABLE $table");
		$this->sql("delete from ".ARX_DB_TABLE_PREFIX."admin_tableAlias where tabl = '$table'");
		heder('self');
	}

	function checkField($table,$field)
	{
		if (!$table || !$field) return 0;
		$ch = $this->sql("select * from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where tabl = '$table' and field = '$field'",1);
		if ($ch) return 0;
		/*            $allFields = $this->sql("select * from $table limit 1",1);
		foreach ($allFields as $key=>$val)
		{
		if ($key == $field) return 0;
		}
		*/
		return 1;
	}

	function changeParentTable()
	{
		$parent_id = r_p("parent_id");
		$table = r_p("table");
		$this->sql("UPDATE ".ARX_DB_TABLE_PREFIX."admin_tableAlias SET parent_id='$parent_id' WHERE tabl='$table'");
		return $this->tableInfo();
	}

	function newField()
	{
		$field_alias = r_p("field_alias");
		$field_name = r_p("field_name");
		$field_type = r_p("field_type");
		$field_default = r_p("field_default");
		$table = $this->t;
		if (!$field_alias || !$field_name || !$field_type || !$table) return 1;
		if (!$this->checkField($table,$field_name)) return 2;
		$field_name = "c_".$field_name;
		$arr['alias'] = $field_alias;
		$arr['type'] = $field_type;
		$arr['tabl'] = $table;
		$arr['field'] = $field_name;
		$arr['def_value'] = $field_default;
		$arr['ch'] = 1;
		$field_type2 = $this->sql("select db_type from ".ARX_DB_TABLE_PREFIX."admin_fieldTypes where id='$field_type'",2,'db_type');
		if($field_type!=11 && $field_type!=12) $this->sql("ALTER TABLE `".$table."` ADD `".$field_name."` ".$field_type2." NULL");
		$this->insert_("admin_fieldAlias",$arr);
		return $this->tableInfo();
	}
	function alertField()
	{
		$table = $this->t;
		//            $table = r_p("table");
		$field = r_p("field");
		$newType = r_p("newType");
		if(!$table || !$field) return;
		if ($newType == 0)
		{
			$fieldName = $this->sql("select field from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where id = '$field'",2,"field");
			$this->sql("delete from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where id = '$field'",3);
			$this->sql("ALTER TABLE `".$table."` DROP `".$fieldName."`");
		}
		else
		{
			switch($newType)
			{
				case 11:
					// это Smarty Checkbox, поэтому удалим поле в таблице, оно больше не нужно, НО запись о нём оставим
					$fieldName = $this->sql("select field from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where id = '$field'",2,"field");
					$this->sql("ALTER TABLE `".$table."` DROP `".$fieldName."`");
					// обновляем запись о типе поля
					$this->update_("admin_fieldAlias",array("type"=>$newType),"id = '$field'");
					break;

				default:
					$old = $this->sql("select field from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where id = '$field'",2,'field');
					$db_type = $this->sql("select db_type from ".ARX_DB_TABLE_PREFIX."admin_fieldTypes where id = '$newType'",2,'db_type');
					$this->sql("ALTER TABLE $table CHANGE $old $old $db_type CHARACTER SET cp1251 COLLATE cp1251_general_ci NOT NULL");
					$this->update_("admin_fieldAlias",array("type"=>$newType),"id = '$field'");
					break;
			}
		}
		return $this->tableInfo();
	}
	function alertCombo()
	{
		//            $table = r_p("table");
		$table = $this->t;
		$field = r_p("field");
		$newCombo = r_p("newCombo");
		if(!$table || !$field ) return $this->tableInfo();
		if (!$newCombo)
		{
			$this->sql("update ".ARX_DB_TABLE_PREFIX."admin_fieldAlias set combo = '',comboField='' where id = '$field'");
		}
		else
		{
			if (!is_numeric($newCombo))
			{
				$new['tabl'] = $newCombo;
				$new['field'] = 'id';
			}
			else
			{
				$new = $this->sql("select field,tabl from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where id='$newCombo'",1);
			}
			$this->sql("update ".ARX_DB_TABLE_PREFIX."admin_fieldAlias set combo = '$new[tabl]',comboField = '$new[field]' where id = '$field'");
		}

		return $this->tableInfo();
	}

	function alertSmartyCheckbox()
	{
		$table = r_p("table");
		$field = r_p("field");
		$newCombo = r_p("newCombo");
		// узнаем данные с помощью которых создадим имя для новой таблицы данных
		$field_parent = mysql_fetch_assoc(mysql_query("SELECT * FROM ".ARX_DB_TABLE_PREFIX."admin_fieldAlias WHERE id=$field"));
		$field_child  = mysql_fetch_assoc(mysql_query("SELECT * FROM ".ARX_DB_TABLE_PREFIX."admin_fieldAlias WHERE id=$newCombo"));
		$table_id=mysql_result(mysql_query("SELECT id FROM ".ARX_DB_TABLE_PREFIX."admin_tableAlias WHERE tabl='$table'"),0,0);
		// формируем имя таблицы
		$table_name=$table."_and_".str_replace("cnt_", "", $this->stripPrefix($field_child['tabl']));
		//
		// удаляем таблицу старых связей
		$this->sql("DROP TABLE IF EXISTS $field_parent[def_value]");

		if(!$table || !$field ) return $this->tableInfo();
		if (!$newCombo)
		{
			$this->sql("update ".ARX_DB_TABLE_PREFIX."admin_fieldAlias set combo = '',comboField='' where id = '$field'");
		}
		else
		{
			if (!is_numeric($newCombo))
			{
				$new['tabl'] = $newCombo;
				$new['field'] = 'id';
			}
			else
			{
				$new = $this->sql("select field,tabl from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where id='$newCombo'",1);
			}
			$key_field=str_replace("cnt_", "", $this->stripPrefix($table))."_id";
			$this->sql("update ".ARX_DB_TABLE_PREFIX."admin_fieldAlias set dest='$key_field', combo = '$new[tabl]',comboField = '$new[field]' where id = '$field'");


			// если таблица связей не создана - создаем её
			$table_list=mysql_list_tables(DB_DATABASE);
			$exists=false;
			while($t=mysql_fetch_array($table_list))
			{
				if($t[0]==$table_name)
				$exists=true;
			}
			// если таблицы нету - создадим её
			if(!$exists)
			{
				if ($this->sql("CREATE TABLE $table_name (`id` INT NOT NULL AUTO_INCREMENT , $key_field INT NOT NULL, ".substr($field_child['field'], 2)."_id INT NOT NULL, PRIMARY KEY ( `id` ))",3))
				$this->sql("update ".ARX_DB_TABLE_PREFIX."admin_fieldAlias SET def_value = '$table_name' WHERE id='$field'");
			}
		}

		return $this->tableInfo();
	}

	function alertExtraTable()
	{
		//            $table = r_p("table");
		$table = $this->t;
		$field = r_p("field");
		$extraTable = r_p("extraTable");
		if(!$table || !$field ) return $this->tableInfo();
		if (!$extraTable)
		{
			$this->sql("update ".ARX_DB_TABLE_PREFIX."admin_fieldAlias set combo = '',comboField='', def_value='', where id = '$field'");
		}

		// узнаем имя выбранной таблицы
		$ex_table=$this->sql("SELECT * FROM ".ARX_DB_TABLE_PREFIX."admin_tableAlias WHERE id='$extraTable'", 1);
		$this->sql("update ".ARX_DB_TABLE_PREFIX."admin_fieldAlias set def_value = '$ex_table[tabl]', combo = '$ex_table[alias]' where id = '$field'");
		return $this->tableInfo();
	}

	function alertDepend()
	{
		$table = $this->t;
		$field = r_p("field");
		$newCombo = r_p("newCombo");
		if(!$table || !$field ) return $this->tableInfo();
		$this->sql("update ".ARX_DB_TABLE_PREFIX."admin_fieldAlias set depend = '$newCombo' where id = '$field'");
		$this->sql("update ".ARX_DB_TABLE_PREFIX."admin_fieldAlias set dependon = '$field' where id = '$newCombo'");

		return $this->tableInfo();
	}

	function alertPsevdo()
	{
		$table = $this->t;
		$field = r_p("field");
		$newCombo = r_p("newCombo");
		if(!$table || !$field ) return $this->tableInfo();
		$this->sql("update ".ARX_DB_TABLE_PREFIX."admin_fieldAlias set psevdo = '$newCombo' where id = '$field'");
		return $this->tableInfo();
	}


	function alertRadio()
	{
		$id = r_p("field");
		if(!$id) return $this->tableInfo();
		$old = $this->sql("select * from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where id = '$id'",2,'tabl');
		$this->sql("update ".ARX_DB_TABLE_PREFIX."admin_fieldAlias set radio = 0 where tabl = '$old'");
		$this->sql("update ".ARX_DB_TABLE_PREFIX."admin_fieldAlias set radio = 1 where id = '$id'");
		return $this->tableInfo();
	}

	function alertAlias()
	{
		$id = r_p("field");
		$alias = r_p("new");
		$type = r_p("type");
		if(!$type) {if (!preg_match("/^(?:[0-9a-zA-Z\s]+)|(?:[0-9а-яА-Я\s])$/",trim($alias))) return $this->errF(1); }
		if(!$id) return $this->tableInfo();
		$this->t = $this->sql("select tabl from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where id = '$id'",2,'tabl');
		$f_type = $this->sql("select type from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where id = '$id'",2,'type');
		if ($alias == 'null') return  $this->tableInfo();
		$f=($type)? $type : "alias";
		switch($f_type)
		{
			case 11:
				if($type=="def_value")
				{
					// это SmartyCheckbox, его def_value отвечает за имя таблицы связей
					// поэтому будем переименовывать её
					$old_table = $this->sql("select def_value from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where id = '$id'",2,'def_value');
					$this->sql("ALTER TABLE $old_table RENAME $alias");
				}
				break;

		}
		$this->sql("update ".ARX_DB_TABLE_PREFIX."admin_fieldAlias set $f = '$alias' where id = '$id'");
		return $this->tableInfo();
	}

	function alertOrder()
	{
		$id = r_p("field");
		$change = r_p("change");
		$this->t = $this->sql("select tabl from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where id = '$id'",2,'tabl');
		$cur = $this->sql("select * from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where id = '$id'",1);
		if ($change == 'up')
		{
			$new = $cur['ord'] - 1;
		}
		else
		{
			$new = $cur['ord'] + 1;
		}
		$neighbour = $this->sql("select * from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where ord = '$new' and tabl = '$cur[tabl]'",1);
		if ($neighbour)
		{
			$this->sql("update ".ARX_DB_TABLE_PREFIX."admin_fieldAlias set ord = '$neighbour[ord]' where id = '$cur[id]'");
			$this->sql("update ".ARX_DB_TABLE_PREFIX."admin_fieldAlias set ord = '$cur[ord]' where id = '$neighbour[id]'");
		}
		else
		{
			$this->sql("update ".ARX_DB_TABLE_PREFIX."admin_fieldAlias set ord = '$new' where id = '$cur[id]'");
		}
		return $this->tableInfo();
	}


	function alertCheckValue()
	{
		$id = r_p("id");
		$tabl = $this->t;
		//            $tabl = r_p("table");
		if(!$id) return $this->tableInfo();
		$old = 0;
		if ($_POST['state'] == 'true') $old = 1;
		$this->sql("update ".ARX_DB_TABLE_PREFIX."admin_fieldAlias set combovalue = '$old' where id = '$id'");
		return $this->tableInfo();
	}

	function alertCheck()
	{
		$id = r_p("field");
		$tabl = $this->t;
		//            $tabl = r_p("table");
		if(!$id) return $this->tableInfo();
		$isLast = $this->sql("select count(*) as c from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where tabl = '$tabl' and ch='1'",2,'c');
		$old = $this->sql("select * from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where id = '$id'",2,'ch');
		if ($old == 1)
		{
			$old = 0;
			if ($isLast <=1 ) $this->errF(7);
		}
		else
		{
			$old = 1;
		}
		$this->sql("update ".ARX_DB_TABLE_PREFIX."admin_fieldAlias set ch = '$old' where id = '$id'");
		return $this->tableInfo();
	}


	function buildJQueryString($alias)
	{
		$ret = '';
		foreach ($alias as $key=>$val)
		{
			if ($val['type'] == 'checkBox')
			{
				$ret .= $val['field'].'="+get_("'.$val['id'].'","c","1")+"&';
			}
			elseif($val['type'] == 'fckeditor')
			{
				$ret .= $val['field'].'="+getFCK("'.$val['id'].'")+"&';
			}
            elseif($val['type'] == 'w_extended')
			{
				$ret .= $val['field'].'="+getMCE("'.$val['id'].'")+"&';
			}
			else
			{
				$ret .= $val['field'].'="+get_("'.$val['id'].'","v","1")+"&';

			}
		}
		return $ret;
	}

	/*
	function buildJQueryString($alias)
	{
	$ret = '';
	foreach ($alias as $key=>$val)
	{
	if ($val['type'] == 'checkBox')
	{
	$ret .= $val['field'].'="+$("#'.$val['id'].'").attr("checked")+"&';
	}
	else
	{
	$ret .= $val['field'].'="+$("#'.$val['id'].'").attr("value")+"&';
	}
	}
	return $ret;

	}

	*/
	//просмотр контента таблицы
	function tableAddRow()
	{
		global $smarty;
		$table = $this->t;
		$type = $this->sql("select * from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where tabl='$table'");
		foreach ($type as $key=>$val)
		{
			if ($val['type'] == 6 || $val['type'] == 9 || $val['type'] == 11 || $val['combovalue'])
			{
				$comboField = $val['comboField'];
				if ($comboField == 'id')
				{
					//  $comboField = $this->sql("select field from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where tabl = '$val[combo]' and radio = 1",2,'field');
				}
				if ($comboField) $comboField2 = ','.$comboField;
				//                      var_dump("select id$comboField from $val[combo]");
				$ord = '';
				$ord = $this->sql("select * from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where tabl='$val[combo]' and field = 'c_name'",1);
				if ($ord) $ord = 'order by c_name asc'; else $ord = '';
				$combo[$val['id']]['items'] = $this->sql("select id$comboField2 from $val[combo] $ord");
				if (!$comboField) $comboField = 'id';
				$combo[$val['id']]['field'] = $comboField;
			}
		}
		$smarty->assign("combo",$combo);
		$aliasAll = $this->sql("select t1.depend,t1.radio,t1.dependon,t1.id,t1.combovalue,t1.alias,t1.field,t2.name as type from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias t1 LEFT JOIN ".ARX_DB_TABLE_PREFIX."admin_fieldTypes t2 ON t1.type = t2.id where t1.tabl = '$table' order by t1.ord");
		$smarty->assign("aliasAll",$aliasAll);
		$smarty->assign("table_name",$table);
		$smarty->assign("fields",$this->buildJQueryString($aliasAll));
		return $smarty->fetch("myAdmin/tableAddRow.sm");
	}



	function tableView($system = "",$id = 0,$rows = '')
	{
		if ($_POST['search'] == 'clearsearch')
		{
			$_SESSION['lastSearch'] = '';
			$_SESSION['lastSearchT'] = '';
		}
		if ($_SESSION['lastSearch'] && $_SESSION['lastSearchT'] == $this->t && $system != '-1')
		{
			$rows = $this->sql("select * from $this->t where $_SESSION[lastSearch]");
			if ($rows)
			{
				return $this->tableView('-1',0,$rows);
			}
		}


		$table = $this->t;

		global $smarty;
		if ($system == 'system')
		{
			$smarty->assign("tableAlias","Текстовые блоки сайта");
		}
		else
		{
			$smarty->assign("tableAlias",$this->getTableAlias($table));
		}
		if ($id)
		{
			$rows = $this->sql("select * from $table where id = '$id'");
		}
		elseif (!$rows)
		{
			$shownFields = $this->sql("select * from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where tabl = '$table' and ch=1");
			$fs = '';
			if ($_SESSION['t'] == $this->t && $_SESSION['tford'] && $_SESSION['tfid'])
			{
				$sortField = $this->sql("select * from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where id='$_SESSION[tfid]'",1);
				$groupTable = '';
				if ($sortField['combo'])
				{
					$fs[] = "t2.*";
					//                        $fs[] = "t2.$sortField[field]";
					$groupTable = " LEFT JOIN ".$sortField['combo']." t2 ";
					//                        $this->sql("select tabl from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where id='$_SESSION[tfid]'",2,'tabl');
					$groupTable .= " ON t1.$sortField[field] = t2.id";
					$sortField = "order by t2.".$sortField['comboField'];
				}
				else
				{
					$sortField = " order by t1.$sortField[field] ";
				}
				$tford = $_SESSION['tford'];
			}
			foreach ($shownFields as $key=>$val)
			{
				if($val['type']!=11 && $val['type']!=12)
				$fs[] = "t1.".$val['field'];
				// не показываем поле доп. таблицы
				if($val['type']==12)
				{
					unset($shownFields[$key]);
				}
			}

			$fs = implode(',',$fs);
			if ($fs != '')
			{
				$fs .= ",t1.id";
			}
			else
			{
				$fs = 't1.id';
			}
			$tford=($tford)? $tford : 'ORDER BY t1.id DESC';
			// extra filter
			$key_field=$this->sql("SELECT field FROM ".ARX_DB_TABLE_PREFIX."admin_fieldAlias WHERE tabl='$table' AND radio=1",1);
			if($key_field && $_SESSION['key_field_value'])
			{
				$extra_filter=($groupTable)? " AND t1.$key_field[field] = '$_SESSION[key_field_value]'" : "WHERE t1.$key_field[field] = '$_SESSION[key_field_value]'";
			}
			//
			$page = r_p("p"); if (!$page) $page = 1;
			$res = mysql_query("select SQL_CALC_FOUND_ROWS $fs from $table t1 $groupTable $extra_filter $sortField $tford limit ".(($page-1)*$this->perPage).",$this->perPage");
			//                print "select SQL_CALC_FOUND_ROWS $fs from $table t1 $groupTable $extra_filter $sortField $tford limit ".(($page-1)*$this->perPage);
			if (!$rows)
			{
				$totalRows	= mysql_result(mysql_query("SELECT FOUND_ROWS()"),0,0);
				$pages = ceil($totalRows/$this->perPage);
			}
			while($r=mysql_fetch_assoc($res))
			{
				// добавляем Smarty элементы
				foreach($shownFields as $field)
				{
					if($field['type']==11)
					{
						$res2=mysql_query("SELECT * FROM $field[def_value] WHERE $field[dest] = '$r[id]'");
						$arr=array();
						$dep_field=substr($field['comboField'], 2)."_id";
						while($r2=mysql_fetch_assoc($res2))
						{
							$arr[]=@mysql_result(mysql_query("SELECT $field[comboField] FROM $field[combo] WHERE id='".$r2[$dep_field]."'"),0,0);
						}
						$r[$field['field']]=$arr;
					}
				}

				$rows[]=$r;
			}
		}
		$type = $this->sql("select * from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where tabl='$table'");
		foreach ($type as $key=>$val)
		{
			if ($val['type'] == 7)
			{
				$_SESSION['photoSize'][$val['id']]['height'] = $val['height'];
				$_SESSION['photoSize'][$val['id']]['width'] = $val['width'];
			}
			if ((($val['type'] == 6)&&($val['combovalue'] == 0)) || $val['type'] == 9)
			{
				$comboField = $val['comboField'];
				if ($comboField == 'id')
				{
					//                        $comboField = $this->sql("select field from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where tabl = '$val[combo]' and radio = 1",2,'field');
				}
				$combo[$val['id']]['items'] = $this->sql("select id, $comboField from $val[combo]");
				$combo[$val['id']]['field'] = $comboField;
				if($rows)
				{
					foreach ($rows as $keyy=>$vall)
					{
						if ($val['psevdo'])
						{
							$psevdo = $this->sql("select * from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where id='".$val['psevdo']."'",1);
							$rows[$keyy][$val['field']] = $this->sql("select $psevdo[field] from $psevdo[tabl] where id =".$rows[$keyy][$val['field']],2,$psevdo['field']);
						}
						else
						{
							$rows[$keyy][$val['field']] = $this->sql("select $comboField from $val[combo] where id = '".$vall[$val['field']]."'",2,$comboField);
						}
					}
				}
			}
		}
		$smarty->assign("rows",$rows);
		$smarty->assign("table",$table);
		$smarty->assign("combo",$combo);
		$tmp = $this->sql("select * from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where tabl = '$table' and ch=1");
		foreach ($tmp as $val)
		{
			$tmp2 .= "'".$val['field']."',";
		}
		$tmp2 = substr($tmp2,0,-1);
		$alias = $this->sql(
		"select t1.*,t2.name as 'type' from ".
		ARX_DB_TABLE_PREFIX."admin_fieldAlias t1 LEFT JOIN ".
		ARX_DB_TABLE_PREFIX."admin_fieldTypes t2 ON t1.type = t2.id where
            t1.tabl = '$table' and t1.field in ($tmp2) and t2.id!=12 order by t1.ord");

		$aliasAll = $this->sql("select t1.depend,t1.dependon,t1.id,t1.alias,t1.field,t2.name as type from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias t1 LEFT JOIN ".ARX_DB_TABLE_PREFIX."admin_fieldTypes t2 ON t1.type = t2.id where t1.tabl = '$table' order by t1.ord");
		$smarty->assign("alias",$alias);
		$smarty->assign("aliasAll",$aliasAll);
		$smarty->assign("fields",$this->buildJQueryString($aliasAll));
		$smarty->assign("system",$system);
		$smarty->assign("pages",$pages);

		return $smarty->fetch("myAdmin/tableView.sm");
		//            return "js|initTableWidget('tabdleView','100%','100%',Array('S'));|".$smarty->fetch("myAdmin/tableView.sm");


	}

	function stripPrefix($table)
	{
		return substr($table,strlen(ARX_DB_TABLE_PREFIX));
	}

	function newValue()
	{
		$table = r_p("table");
		$id = r_p("id");
		$edit_flag = r_p("edit");
		$fields = $this->getFields($table);
		$qShowStatus 		= "SHOW TABLE STATUS LIKE '$table'";
		$qShowStatusResult 	= mysql_query($qShowStatus);
		$row = mysql_fetch_assoc($qShowStatusResult);
		$next_id = $row['Auto_increment'];
		$fillNewTable=false;
		if(!$id) $insert['id']=$next_id;
		$m_id=($id)? $id : $next_id;
		if($_SESSION['key_field_value']) $m_id=$_SESSION['key_field_value'];
		foreach ($fields as $key=>$val)
		{
			//                $insert[$val['field']] = r_p($val['field']);
			if($val['type']!=11 && $val['type']!=12) { $insert[$val['field']] = $_REQUEST[$val['field']];}
			// если поле не заполнено, найдем его значение по умолчанию
			if (empty($insert[$val['field']]) && $val['type']!=11 && $val['type']!=12)
			{
				$def_val=@mysql_result(mysql_query("SELECT def_value FROM ".ARX_DB_TABLE_PREFIX."admin_fieldAlias WHERE tabl='$table' AND field='$val[field]'"),0,0);
				$insert[$val['field']]=$def_val;
			}
			if ($val['type'] == 10)
			{
				if ($insert[$val['field']] == 'true')
				{
					$insert[$val['field']] = '1';
				}
				else
				{
					$insert[$val['field']] = '0';
				}
			}
			if ($val['type'] == 11)
			{
				$field=mysql_fetch_assoc(mysql_query("SELECT * FROM ".ARX_DB_TABLE_PREFIX."admin_fieldAlias WHERE tabl='$table' AND field='$val[field]'"));
				// удаляем все имеющиеся записи о связях если мы редактируем запись
				$key_field=$field['dest'];
				$dep_field=substr($field['comboField'], 2)."_id";
				if($id)	mysql_query("DELETE FROM $field[def_value] WHERE $key_field = '$id'");
				// id

				// добавляем записи о связях
				$values=explode("|", $_POST[$val['field']]);
				foreach ($values as $item)
				{
					if(!empty($item))
					{
						mysql_query("INSERT INTO $field[def_value] SET $key_field = '$m_id', $dep_field = '$item'");
					}
				}
			}

			if ($val['type'] == 12)
			{
				$fillNewTable=true;
				$_SESSION['key_field_value']=$m_id;
				$_SESSION['key_table']=$table;
				$fillNewTableName=mysql_result(mysql_query("SELECT def_value FROM ".ARX_DB_TABLE_PREFIX."admin_fieldAlias WHERE tabl='$table' AND field='$val[field]'"),0,0);
				$table_info=$this->sql("SELECT * FROM ".ARX_DB_TABLE_PREFIX."admin_tableAlias WHERE tabl='$table'",1);
				$_SESSION['key_table_name']=$table_info['alias'];
			}
		}
		if ($id)
		{
			$insert['letime'] = time();
			$this->update_($this->stripPrefix($table),$insert," id = '$id'");
		}
		else
		{
			$insert['time'] = time();
			$this->insert_($this->stripPrefix($table),$insert);
		}
		//
		if(!$fillNewTable)
		{
			if (r_p('addmore')== 'true')
			{
				return $this->tableAddRow();
			}
			else
			{
				if($_SESSION['key_table']) $this->t=$_SESSION['key_table'];
				// очищаем данные сессии о визарде
				unset($_SESSION['key_field_value']);
				unset($_SESSION['key_table']);
				return ($this->tableView());
			}
		}
		else
		{
			if(!$edit_flag)
			{
				$this->t=$fillNewTableName;
				return $this->tableAddRow();
			}
			else
			{
				$this->t=$fillNewTableName;
				return $this->tableView();
			}
		}
	}

	function destroy_extra_session()
	{
		if($_SESSION['key_table']) $this->t=$_SESSION['key_table'];
		// очищаем данные сессии о визарде
		unset($_SESSION['key_field_value']);
		unset($_SESSION['key_table']);
		return ($this->tableView());
	}

	function deleteRow()
	{

		$table = $this->t;
		$id = r_p("id");
		$this->sql("delete from $table where id = '$id'");
		return $this->tableView();

		/*
		$table = $this->t;
		$id = r_p("id");

		$row = $this->sql("select * from $table where id = '$id'",1);
		$combo = $this->sql("select * from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where combo = '$this->t'");
		foreach ($combo as $key=>$val)
		{
		foreach ($row as $keyy=>$vall)
		{

		}
		}
		$this->sql("delete from $table where id = '$id'");
		return $this->tableView();
		*/
	}

	function deleteRows()
	{

		$table = $this->t;
		$id = r_p("id");
		$id_list=explode("|", $id);
		foreach($id_list as $val)
		{
			$this->sql("delete from $table where id = '$val'");
		}
		return $this->tableView();
	}

	function exportStruct()
	{
		$tables = $this->sql("select * from ".ARX_DB_TABLE_PREFIX."admin_tableAlias");
		foreach ($tables as $key=>$val)
		{
			$tables[$key]['fields'] = $this->getFields($val['tabl']);
			foreach ($tables[$key]['fields'] as $keyy=>$vall)
			{
				$tables[$key]['fields'][$keyy]['type'] = $this->sql("select alias from ".ARX_DB_TABLE_PREFIX."admin_fieldTypes where id = $vall[type]",2,'alias');
			}
		}
		global $smarty;
		$smarty->assign("struct",$tables);
		return $smarty->fetch("myAdmin/struct.sm");

	}

	function editValue()
	{
		global $smarty;
		$table = $this->t;
		$id = r_p("id");
		if (!$id) return $this->tableView();

		$row = $this->sql("select * from $table where id = '$id'",1);
		$type = $this->sql("select * from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where tabl='$table'");
		foreach ($type as $key=>$val)
		{
			if ($val['type'] == 6 || $val['type'] == 9)
			{
				$comboField = $val['comboField'];
				if ($val['psevdo'])
				{
					$psevdo = $this->sql("select * from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where id='".$val['psevdo']."'",1);
					$combo[$val['id']]['items'] = $this->sql("select t1.id,t1.$psevdo[field] from $val[combo] t1 LEFT JOIN $psevdo[tabl] t2 on t1.id=t2.$val[comboField]");
					$combo[$val['id']]['field'] = $psevdo['field'];
				}
				else
				{
					$combo[$val['id']]['items'] = $this->sql("select id,$comboField from $val[combo]");
					$combo[$val['id']]['field'] = $comboField;
					//                        $row[$val['field']] = $this->sql("select $comboField from $val[combo] where id = '".$vall[$val['field']]."'",2,$comboField);
				}
			}
			if ($val['type'] == 11)
			{
				$dep_field=substr($val['comboField'], 2)."_id";
				$row[$val['field']]['all']=$this->sql("SELECT id, $val[comboField] AS combo FROM $val[combo]");
				$row[$val['field']]['selected']=$this->sql("SELECT $dep_field AS selected FROM $val[def_value] WHERE $val[dest] = '$row[id]'");
			}
			if ($val['type'] == 2)
			{
				//                    $row[$val['field']] = htmlentities($row[$val['field']]);
			}
			else
			{
				//                    $row[$val['field']] = htmlentities($row[$val['field']]);
			}
		}
		foreach ($row as $key=>$val)
		{
			//                $row[$key] =  htmlentities($val);
		}
		$smarty->assign("row",$row);
		$smarty->assign("combo",$combo);
		$alias = $this->sql("select t1.dest,t1.depend,t1.dependon,t1.id,t1.combovalue,t1.alias,t1.field,t2.name as type from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias t1 LEFT JOIN ".ARX_DB_TABLE_PREFIX."admin_fieldTypes t2 ON t1.type = t2.id where t1.tabl = '$table' ");
		$smarty->assign("alias",$alias);
		$smarty->assign("fields",$this->buildJQueryString($alias));
		return $smarty->fetch("myAdmin/rowView.sm");
	}

	//сугубо для проекта ГАЗЕТА ВРЕМЕНИ
	function parentChild()
	{
		$id = r_p("id");
		$selected = r_p("selected");
		$source = r_p("source");
		$source = $this->sql("select * from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where id = '$source' ",1);
		$field = $this->sql("select * from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where id = '$id' ",1);
		$psevdo = $this->sql("select * from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where id = '$field[psevdo]' ",1);
		$fieldParent = $this->sql("select * from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where tabl = '$field[combo]' and type=6",1);
		$ret = 'select|'.$id.'|';
		if ($psevdo)
		{
			$selected = $this->sql("select c_rubrikType from new__cnt_nomer where id = '$selected'",2,'c_rubrikType');
			$res = $this->sql("select id,$psevdo[field] from $psevdo[tabl] where id in (select $field[comboField] from $field[combo] where c_nomer = '$selected')");
			foreach ($res as $key=>$val)
			{
				//                    $ret .= "<option value='".$val['id']."'>".$val[$psevdo['field']]."</option>";
				$ret .= $val['id'].";".$val[$psevdo['field']].";";
			}
		}
		else
		{
			$res = $this->sql("select id,$field[comboField] from $field[combo] where $fieldParent[field] = '$selected'");
			foreach ($res as $key=>$val)
			{
				//                    $ret .= "<option value='".$val['id']."'>".$val[$field['comboField']]."</option>";
				$ret .= $val['id'].";".$val[$field['comboField']].";";
			}
		}
		return $ret;
	}
	function alertSize()
	{
		$id = r_p("id");
		$H = r_p('H');
		$W = r_p('W');
		$Hth = r_p('Hth');
		$Wth = r_p('Wth');
		$dest = r_p('dest');
		$prefix = r_p('prefix');
		$this->sql("update ".ARX_DB_TABLE_PREFIX."admin_fieldAlias set dest = '$dest', prefix = '$prefix', width = '$W',height='$H',widthth = '$Wth',heightth = '$Hth' where id='$id'");
		$this->t = $this->sql("select tabl from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where id='$id'",2,'tabl');
		return $this->tableInfo();
	}

	function table_select($parent_id=0, $padding=null, $selected=null)
	{
		$html='';
		//рекурсивно ищем таблицы и возвращаем их ввиде вложенного массива
		$res=mysql_query("SELECT * FROM ".ARX_DB_TABLE_PREFIX."admin_tableAlias WHERE parent_id=$parent_id");
		while($row=mysql_fetch_assoc($res))
		{
			//ищем потомков
			$sel=($row['tabl']==$selected)? "selected" : '';
			$html.="<option value='$row[id]' $sel>$padding $row[alias]</option>";
			$html.=$this->table_select($row['id'], $padding."&gt;");
		}
		return $html;
	}

	function newTableForm()
	{
		global $smarty;
		$smarty->assign("table_select", $this->table_select());
		return $smarty->fetch("myAdmin/tableNew.sm");
	}

	function tableSearch()
	{
		global $smarty;
		if (r_p("search"))
		{
			$qString = '';
			$fields = explode('|',r_p("sFields"));
			foreach ($fields as $key=>$val)
			{
				//                    $r_p = addslashes(urldecode($this->decode->_ucs2EntitiesDecode(r_p($val))));
				$r_p = $_POST[$val];
				if ($r_p != '')
				{
					$like = "";
					$quote = "'";
					$valop = $_POST[$val.'op'];
					if ($valop == 'Like') $like = '%';

					$alias = $this->sql("select * from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where tabl='$this->t' and field = '$val'",1);
					if ($alias['combo'] && $alias['comboField'])
					{
						$r_p2 = $this->sql("select id from $alias[combo] where $alias[comboField] $valop $quote$like$r_p$like$quote");
						if ($r_p2)
						{
							$r_p = '(';
							foreach ($r_p2 as $keyy=>$vall)
							{
								$r_p .= "'$vall[id]',";

							}
							$r_p = substr($r_p,0,-1);
							$r_p .= ')';
							$like = '';
							$valop = 'in';
							$quote = "";
						}
					}
					$qString .= "$val $valop $quote$like$r_p$like$quote and ";
				}
			}
			$qString = substr($qString,0,-5);
			$_SESSION['lastSearch'] = $qString;
			$_SESSION['lastSearchT'] = $this->t;
			$rows = $this->sql("select * from $this->t where $qString");
			if ($rows)
			{
				return $this->tableView('',0,$rows);
			}
			else
			{
				$smarty->assign("err",1);
			}
		}
		$table = $this->t;
		$aliasAll = $this->sql("select t1.depend,t1.dependon,t1.id,t1.alias,t1.field,t2.name as type from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias t1 LEFT JOIN ".ARX_DB_TABLE_PREFIX."admin_fieldTypes t2 ON t1.type = t2.id where t1.tabl = '$table' order by t1.ord");
		$smarty->assign("aliasAll",$aliasAll);
		$sString = '';
		$sFields = '';
		foreach ($aliasAll as $key=>$val)
		{
			$sString .= $val['field'].'="+get_("'.$val['id'].'","v","1")+"&'.$val['field'].'op="+get_("'.$val['id'].'op","v","1")+"&';
			$sFields .= $val['field']."|";
		}
		$sString .= 'sFields='.$sFields."&";
		$smarty->assign("fields",$sString);
		return $smarty->fetch("myAdmin/tableSearch.sm");
	}
	//обработка аякс запросовв
	function ajaz()
	{
		global $smarty;
		$page = r_p("page");
		$this->t = r_p("table");
		switch($page)
		{
			case "changeParentTable":        return $this->changeParentTable();     break;
			case "destroy_extra_session":        return $this->destroy_extra_session();     break;
			case "intro":        return $smarty->fetch("myAdmin/intro.sm");    break;
			case "tableInfo":    return $this->tableInfo();                    break;
			case "tableView":    return $this->tableView();                    break;
			case "tableAddRow":    return $this->tableAddRow();                    break;
			case "tableSearch":    return $this->tableSearch();                    break;
			case "newTableForm": return $this->newTableForm(); break;
			case "newTable":     return $this->newTable();                     break;
			case "deleteTable":  return $this->deleteTable();                  break;
			case "alertField":   return $this->alertField();                   break;
			case "newField":     return $this->newField();                            break;
			case "newValue":     return $this->newValue();                     break;
			case "editValue":    return $this->editValue();                    break;
			case "deleteRow":    return $this->deleteRow();                    break;
			case "deleteRows":    return $this->deleteRows();                    break;
			case "exportStruct": return $this->exportStruct();                 break;
			case "system":       return $this->tableView("system");            break;
			case "alertCombo":   return $this->alertCombo();                   break;
			case "alertSmartyCheckbox":   return $this->alertSmartyCheckbox();                   break;
			case "alertExtraTable":   return $this->alertExtraTable();                   break;
			case "alertCheck":   return $this->alertCheck();                   break;
			case "alertRadio":   return $this->alertRadio();                   break;
			case "alertDepend":   return $this->alertDepend();                   break;
			case "alertPsevdo":   return $this->alertPsevdo();                   break;
			case "alertSize":   return $this->alertSize();                   break;
			case "alertAlias":   return $this->alertAlias();                   break;
			case "alertOrder":   return $this->alertOrder();                   break;
			case "alertCheckBox":   return $this->alertCheckBox();                   break;
			case "alertSort":   return $this->alertSort();                   break;
			case "alertCheckValue":   return $this->alertCheckValue();                   break;

			case "parentChild":   return $this->parentChild();                   break;
			case "dump":   return  $this->dump();                  break;
			case "db_export":   return  $this->db_export();                  break;
			case "restore":   return  $this->db_restore();                  break;
			case "newplugin":   return  $this->newPlugin();                  break;
			case "sqlManager":   return  $this->sqlManager();                  break;
			case "LanguageManager":   return  $this->LanguageManager();                  break;
			case "tableManager":   return  $this->tableManager();                  break;
		}
	}

	function tableManager()
	{
		global $smarty;

		$id = r_p('id');
		if ($id)
		{
			$arr['recCount'] = intval(r_p('recCount'));
			$arr['tfid'] = intval(r_p('tfid'));
			$arr['tford'] = (r_p('tford'));
			$this->update_('admin_tableAlias',$arr," id = '$id'");
		}
		$tables = $this->sql("select * from ".ARX_DB_TABLE_PREFIX."admin_tableAlias ");
		foreach ($tables as $key=>$val)
		{
			$tables[$key]['recCount'] = $this->sql("select count(*) as count from $val[tabl]",2,'count');
			$tables[$key]['TMsortFieldDefault'] = $this->sql("select alias,id from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where tabl = '$val[tabl]' order by field");

		}
		$smarty->assign("tables",$tables);
		return $smarty->fetch("myAdmin/tableManager.sm");
	}

	function alertSort()
	{
		$_SESSION['t'] = $this->t;
		$_SESSION['tfid'] = r_p("field");
		$_SESSION['tford'] = r_p("order");
		return $this->tableView();
	}

	function alertCheckBox()
	{
		$id = r_p("id");
		$arr['check1'] = ($_POST['cy']);
		$arr['check0'] = ($_POST['cn']);
		$this->update_('admin_fieldAlias',$arr," id = '$id'");
		return $this->tableInfo();
	}
	function LanguageManager()
	{
		global $smarty;
		$lang = r_p('lang');
		$mode = r_p('mode');
		if ($mode)
		{
			$d = r_p('d');
			$id = r_p('id');

			if ($d != '' && $d != 'null' && $d != null)
			{
				if ($mode == 1)
				$this->sql("update ".ARX_DB_TABLE_PREFIX."cms__locale_settings set alias = '$d' where id = '$id'");
				if ($mode == 2)
				$this->sql("update ".ARX_DB_TABLE_PREFIX."cms__locale_settings set value = '$d' where id = '$id'");
				if ($mode == 3)
				{
					$alias = r_p("alias");
					if ($alias)
					{
						$arr['alias'] = $alias;
						$arr['lang_id'] = r_p('langId');
						$arr['value'] = $d;
						$this->insert_('cms__locale_settings',$arr);
					}
				}
				if ($mode == 4)
				{
					$tmp = $this->sql("select langId from ".ARX_DB_TABLE_PREFIX."admin_Langs order by id desc",2,'langId');
					$tmp++;
					$arr['lang'] = $d;
					$arr['langId'] = $tmp++;
					$this->insert_("admin_Langs",$arr);
				}
				if ($mode == 5)
				{
					$arr['alias'] = $d;
					$this->insert_("cms__locale_settings",$arr);
				}
			}
			if ($mode == 'del')
			{
				$alias = r_p('alias');
				$this->sql("delete from ".ARX_DB_TABLE_PREFIX."cms__locale_settings where alias = '$id'");
			}

		}
		$l = $this->sql("select * from ".ARX_DB_TABLE_PREFIX."admin_Langs order by langId");
		$smarty->assign('l',$l);
		$lAlias = $this->sql("select DISTINCT alias from ".ARX_DB_TABLE_PREFIX."cms__locale_settings order by alias");
		foreach ($lAlias as $key=>$val)
		{
			$lAlias[$key]['items'] = $this->sql("select id,lang_id,value from ".ARX_DB_TABLE_PREFIX."cms__locale_settings where alias = '$val[alias]' order by alias,lang_id");
			$lAlias[$key]['count'] = count($l) - count($lAlias[$key]['items']);
		}
		$smarty->assign("lAlias",$lAlias);

		return $smarty->fetch("myAdmin/languageManager.sm");
	}
	function sqlManager()
	{


		global $smarty;

		$smarty->assign("tables",$this->sql("select * from ".ARX_DB_TABLE_PREFIX."admin_tableAlias order by alias"));

		return $smarty->fetch("myAdmin/sqlManager.sm");

	}

	function newPlugin()
	{
		global $smarty;
		$className = r_p('className');
		$classTitle = r_p('classTitle');
		if ($className && $classTitle)
		{
			if (!preg_match("/^[a-zA-Z]{3,}$/", trim($className))) return $this->errF(9);
			if (!preg_match("/^(?:[a-zA-Z\s]+)|(?:[а-яА-Я\s])$/",trim($classTitle))) return $this->errF(10);
			$dest = $_SERVER['DOCUMENT_ROOT'].'/cms/_plugins/';
			$smarty->assign("className",$className);
			$smarty->assign("classTitle",$classTitle);
			$w=fopen($dest."cmsplg__$className.lib.php",'w');
			fwrite($w,$smarty->fetch("myAdmin/pluginTemplate.sm"));
			fclose($w);
		}

		return $smarty->fetch("myAdmin/newPLugin.sm");
	}

	function db_restore()
	{
		$db_link=mysql_connect(DB_SERVER,DB_USER,DB_PASSWORD);
		mysql_select_db(DB_DATABASE,$db_link) ;

		$result = mysql_list_tables(DB_DATABASE);
		for ($i = 0; $i < mysql_num_rows($result); $i++)
		mysql_unbuffered_query("DROP TABLE ".mysql_tablename($result, $i),$db_link);

		$wsql = file_get_contents($_SERVER['DOCUMENT_ROOT'].'/control/myadmin/dump/'.r_p("id"));

		preg_match_all ("/CREATE TABLE([^;])*;/i",$wsql,$ct);
		preg_match_all ("/INSERT INTO.*\);/i",$wsql,$ir);
		$ct=$ct[0];
		$ir=$ir[0];
		foreach ($ct as $val) mysql_unbuffered_query(substr($val,0,strlen($val)),$db_link) ;
		foreach ($ir as $val) mysql_unbuffered_query(substr($val,0,strlen($val)),$db_link) ;
		mysql_close($db_link);
		global $smarty;
		return $smarty->fetch("myAdmin/intro.sm");
	}

	function fileUpload()
	{
		if($_FILES || $_POST['nofile'])
		{
			$id = r_p('id');
			$nW = $this->sql("select width from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where id = '$id'",2,'width');
			$nH = $this->sql("select height from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where id = '$id'",2,'height');
			$nWth = $this->sql("select widthth from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where id = '$id'",2,'widthth');
			$nHth = $this->sql("select heightth from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where id = '$id'",2,'heightth');
			$dest = $this->sql("select dest from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where id = '$id'",2,'dest');
			$prefix = $this->sql("select prefix from ".ARX_DB_TABLE_PREFIX."admin_fieldAlias where id = '$id'",2,'prefix');
			$i = up_image("file",array($nW,$nH,$nWth,$nHth,$dest,$prefix));
			global $smarty;
			$smarty->template_dir = $_SERVER['DOCUMENT_ROOT'];
			return $smarty->fetch("cms/file.html").
			"<script>parent.addPhoto(window.name,'$i','$dest')</script>";
		}
	}

	function getModuleList()
	{
		$table = new CARXTable('cms_modules');
		$data = $table->FetchRows();
		return $data;
	}

	function getModuleAct($mod)
	{
		if ($mod>0)
		{
			$i=0;
			$table = new CARXTable('cms_modules',"id=$mod");
			$data = $table->FetchRow();
			if (file_exists(CMS_PLUGIN_DIR.'/'.$data['plg_file']))
			{
				require_once(CMS_PLUGIN_DIR.'/'.$data['plg_file']);
				$plugClass = str_replace('.lib.php','',$data['plg_file']);
				$plug = new $plugClass;
				$plugParts = $plug->setPluginParts();
				$plugParts['getOutput']='Главное действие';
				$plugParts=array_reverse($plugParts);
				$tplToPart = $plug->setPartTemplates();
				foreach ($plugParts as $k=>$v)
				{
					$res[$i]['func']=$k;
					$res[$i]['alias']=$v;
					$res[$i]['tpl']=$tplToPart[$k];
					$i++;
				}

			}
			return $res;
		}

	}
	//самая главная мегапупер функция
	function GetContent()
	{
		//всеяпланиновый carxtable - есть полная хуйня. Он не нужен.
		global $smarty;
		$smarty->assign('lg',loadLocaleMsg());
		$smarty->assign('locale',loadLocaleMsg());
		$smarty->template_dir = $_SERVER['DOCUMENT_ROOT'].'/control/_templates/cms/';
		$smarty->assign('header',$smarty->fetch("header.tpl"));
		$smarty->assign('footer',$smarty->fetch("footer.tpl"));
		$this->decode = new Decoder();
		foreach ($_POST as $key=>$val)
		{
			$_POST[$key] = urldecode($this->decode->_ucs2EntitiesDecode($val));
		}


		$smarty->template_dir = $_SERVER['DOCUMENT_ROOT'].'/control/myadmin/';
		$this->table = new CARXTable();

		$file = $this->fileUpload();
		if ($file) return $file;
		//если аякс
		$ajaz = r_p("ajaz");

		if ($ajaz)
		{
			if (r_p("page") != 'download')
			header("Content-Type: text/html; charset=".DATABASE_CHARSET);
			echo $this->ajaz();
			exit;
		}
		//просто генерим страницу
		//Закомментим ...
		$smarty->assign("tables",$this->getTableList());

		$smarty->assign('modules',$this->getModuleList());
		return $smarty->fetch("myAdmin/index.sm");
	}

	function dump()
	{
		$dir = $_SERVER['DOCUMENT_ROOT'].'/control/myadmin/dump/';
		if (!$path) $path = $dir.time();
		$dh  = opendir($dir);
		while (false !== ($filename = readdir($dh)))
		{
			if ($filename != '.' && $filename != '..')
			$files[] = $filename;
		}
		asort($files);
		if (count($files) >= 9)
		unlink($dir.$files[0]);
		$i = 1;
		global $smarty;
		$smarty->assign("files",$files);
		return $smarty->fetch("myadmin/dump.sm");

	}
	function db_export($path = '', $is_drop = 1)
	{
		$dir = $_SERVER['DOCUMENT_ROOT'].'/control/myadmin/dump/';
		if (!$path) $path = $dir.time();
		$r_handle = fopen($path, 'w');
		$tables = $this->sql("SHOW TABLES FROM ".DB_DATABASE); //Получим список таблиц.

		$dmp = "# Дамп базы данных: ".DB_DATABASE." \n\n";
		foreach ($tables as $tab) // Запуск цикла, выполняющего дамп
		{
			$tab_name = array_pop($tab);

			if ($is_drop) $dmp.= "-- Drop table ".$tab_name.":\n  DROP TABLE IF EXISTS '".$tab_name."';/n"; // Отображаем SQL-код удаления базы

			$res = $this->sql("SHOW CREATE TABLE $tab_name",1);  // Определяем SQL-код создания базы
			fwrite($r_handle, "\n\n\n-- Структура таблицы $tab_name:\n".
			$res['Create Table']."; \n\n-- Данные:\n\n");

			if ($res = $this->sql("SELECT * FROM $tab_name"))
			foreach($res as $row)
			{
				if (!is_numeric($res))
				{
					// Отображаем SQL-код добавления строки
					$keys = implode("`, `", array_keys($row));
					$values = (array_values($row));
					$valllls = array();
					foreach ($values as $keyyyyy=>$valllll)
					$valllls [] = addslashes($valllll);
					$values = (implode("', '", $valllls));
					fwrite ( $r_handle, "INSERT INTO `$tab_name`(`".$keys."`) VALUES ('".$values."');\n");
				}
			}

		}
		fclose($r_handle);
		return $this->dump();
	}


	//фуфил всякий ненужный

	function getTplContent($modId,$template)
	{
		if ($modId)
		{
			$table = new CARXTable('cms_modules',"id=$modId",'mdl');
			$data = $table->FetchRow();
			if ($data['mdl'] && trim($template))
			{
				$ext = explode('.',$template);
				$ext = array_pop($ext);
				switch ($ext)
				{
					case 'tpl': $tplfile=TEMPLATES_DIR.'/'.$data['mdl'].'/'.$template; break;
					case 'jtpl': $tplfile=JTEMPLATES_DIR.'/'.$data['mdl'].'/'.$template; break;
					default:break;
				}
			}

			$result = file_get_contents($tplfile);
			return $result;
		}
	}

	function saveTemplate($modId,$template,$tplContent)
	{
		if ($modId)
		{
			$table = new CARXTable('cms_modules',"id=$modId",'mdl');
			$data = $table->FetchRow();
			if ($data['mdl'] && trim($template))
			{
				$ext = explode('.',$template);
				$ext = array_pop($ext);
				switch ($ext)
				{
					case 'tpl': $tplfile=TEMPLATES_DIR.'/'.$data['mdl'].'/'.$template; break;
					case 'jtpl': $tplfile=JTEMPLATES_DIR.'/'.$data['mdl'].'/'.$template; break;
					default:break;
				}
				$file=fopen($tplfile,'w');
				$tplContent=stripslashes($tplContent);
				fwrite($file,$tplContent);
				fclose($file);
				return 1;

			}

		}
		
	}
	
	function getInstalledPlg($module)
	{
		if ($module>0)
		{
		$table = new CARXTable('cms_modules',"id=$module",'plg_file');
		$data = $table->FetchRow();
		
		require_once(CMS_PLUGIN_DIR.'/'.$data['plg_file']);
		
		$plg = str_replace('.lib.php','',$data['plg_file']);
		$plugin = new $plg;
		$pluginParts = $plugin->setPluginParts();
		$table = new CARXTable('cms_plugin2page',"plugin='$plg'",'id,page_id,pluginProperties');
		$table->joinTable(ARX_DB_TABLE_PREFIX.'cms_page','t1.page_id=t2.page_id','title');
		$table->SetMode(1,0);
		$data = $table->FetchRows();
		foreach ($data as $k=>$v)
		{
			$data[$k]['pluginProperties']=unserialize($data[$k]['pluginProperties']);
			if ($data[$k]['pluginProperties']['mStartFunction'])
			{
				$data[$k]['action']=$pluginParts[$data[$k]['pluginProperties']['mStartFunction']];
			}
			else 
			{
				$data[$k]['action']='Главное действие';
			}
			unset($data[$k]['pluginProperties']);
		}
		return fetcharray_to_simple_json($data);
		}
		
		
	}
		function updateValidations($fldId,$validator,$req,$minSize,$maxSize,$unique)
		{
			$req = str_replace(array('undefined','true'),array(0,1),$req);
			$unique = str_replace(array('undefined','true'),array(0,1),$unique);
			$table = new CARXTable('admin_fieldAlias',"id=$fldId");
			$table->SetField('validator',$validator);
			$table->SetField('required',$req);
			$table->SetField('minlength',$minSize);
			$table->SetField('maxlength',$maxSize);
			$table->SetField('uniqueFld',$unique);
			$table->Update();
			print_r($table);
		}

	}
?>